package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ReportService reportService;

    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //将x轴中的日期全部添加到list集合中
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            list.add(begin);
        }

        List<Double> turnovers = new ArrayList<>();
        //根据日期获得y轴当天的营业额
        list.forEach(localDate -> {
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            Map<String, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin",min);
            map.put("end",max);
            Double turnover = orderMapper.getTurnover(map);
            //如果营业额为空则修改为0.0
            if(turnover == null){
                turnover = 0.0;
            }
            turnovers.add(turnover);

        });
        //用TurnoverReportVO进行封装
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder().
                turnoverList(StringUtils.join(turnovers,",")).
                dateList(StringUtils.join(list,",")).build();
        return turnoverReportVO;

    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
        //将x轴中的日期全部添加到list集合中
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            list.add(begin);
        }

        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();


        list.forEach(localDate -> {
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            Integer newUser = orderMapper.getUserStatistics(min,max);
            Integer totalUser = orderMapper.getUserStatistics(null, max);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        });
        UserReportVO userReportVO = UserReportVO.builder().dateList(StringUtils.join(list))
                .newUserList(StringUtils.join(newUserList))
                .totalUserList(StringUtils.join(totalUserList)).build();

        return userReportVO;

    }

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getGoodsSale(begin,end);
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String name = StringUtils.join(nameList, ",");
        String number = StringUtils.join(numberList, ",");
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder().nameList(name).numberList(number).build();
        return salesTop10ReportVO;
    }


    /**
     * 根据时间区间统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end){
        // 创建日期数据集合，组装成x轴数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的总订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            //查询每天的有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    @Override
    public void export(HttpServletResponse response) throws IOException {
        //查询最近30天的运营数据
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(beginDay, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endDay, LocalTime.MAX);
        BusinessDataVO bd = workspaceService.getBusinessData(begin, end);
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("static/运营数据报表模板.xlsx");
        XSSFWorkbook xw = new XSSFWorkbook(is);
        XSSFSheet sheet = xw.getSheetAt(0);

        XSSFRow row1 = sheet.getRow(1);
        row1.getCell(1).setCellValue("从"+beginDay+"-"+endDay);

        XSSFRow row4 = sheet.getRow(3);
        row4.getCell(2).setCellValue(bd.getTurnover());
        row4.getCell(4).setCellValue(bd.getOrderCompletionRate());
        row4.getCell(6).setCellValue(bd.getNewUsers());

        XSSFRow row3 = sheet.getRow(4);
        row3.getCell(2).setCellValue(bd.getValidOrderCount());
        row3.getCell(4).setCellValue(bd.getUnitPrice());

        for (int i = 0; i < 30; i++) {
            LocalDate plusDays = beginDay.plusDays(i);
            BusinessDataVO bdd = workspaceService.getBusinessData(LocalDateTime.of(plusDays, LocalTime.MIN), LocalDateTime.of(plusDays, LocalTime.MAX));
            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(plusDays.toString());
            row.getCell(2).setCellValue(bdd.getTurnover());
            row.getCell(3).setCellValue(bdd.getValidOrderCount());
            row.getCell(4).setCellValue(bdd.getOrderCompletionRate());
            row.getCell(5).setCellValue(bdd.getUnitPrice());
            row.getCell(6).setCellValue(bdd.getNewUsers());

        }

        ServletOutputStream os = response.getOutputStream();
        xw.write(os);
        os.close();
        xw.close();
    }






    /**
     * 根据时间区间统计指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin",beginTime);
        map.put("end", endTime);
        return orderMapper.countByMap(map);
    }


}
